<?php
require_once('MySqlConnection.php');
require_once('Salutation.php');

class SalutationDAL{
	
	private $_connection;
	//Singleton pattern
    private static $_instance = null;
	public static function Instance(){
		if (self::$_instance == null) self::$_instance = new SalutationDAL();
		return self::$_instance;
	}
	private function __construct(){
		include_once('./include/db.inc');
		$this->_connection = MySqlConnection::Instance($server,$user,$password,$database);
	}
	
	public function getSalutations(){
		$this->_connection->Open();
		$sqlString = "select * from salutation";
		$resultData = $this->_connection->ExecuteSQL($sqlString, 'O');
		return $this->Mapping($resultData, 'salutation');
	}
	
		public function getSalutationById($salutationId){
		$this->_connection->Open();
		$sqlString = "select * from salutation where id = '{$salutationId}'";
		$resultData = $this->_connection->ExecuteSQL($sqlString, 'O');
		return $this->Mapping($resultData, 'salutation');
	}
	
		public function addSalutation($salutation){
		include('./include/db.inc');
		$mysqli = new mysqli($server, $user, $password, $database);
		if(mysqli_connect_errno()) {
		  echo "Connection Failed: " . mysqli_connect_errno();
		  exit();
		}
		if($stmt = $mysqli->prepare("INSERT INTO salutation(name,sex) VALUES(?,?)"))
		{
			$stmt->bind_param("si", $salutation['name'], $salutation['sex']);
			$success = $stmt->execute();
			if(!$success){
				echo "Inserting salutation failed!";
			}
		}
		else{
			
			echo "Failed preparing insert salutation statement!";
		}
		$mysqli -> close();
	}
	
		//MAPPPING
	
	private function Mapping($queryData,$resultType){
		foreach($queryData as $data){
			$resultArray[] = $this->Map($data,$resultType);
		}
		return $resultArray;
	}
	
	private function Map($data,$resultType){
		$object = new Salutation($data->id,$data->name,$data->sex);
		return $object;
	}
}

